package spring.springbucks.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import spring.springentity.entity.table.CoffeeEntity;
import spring.springentity.repository.CoffeeRepository;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/coffee")
//@RateLimiter(name = "coffee")
@Slf4j
public class CoffeeController {
    @Autowired
    private CoffeeRepository coffeeRepository;

    @PostMapping(path = "/", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    @ResponseStatus(HttpStatus.CREATED)
    public CoffeeEntity addCoffeeWithoutBindingResult(@Valid CoffeeEntity newCoffee) {
        coffeeRepository.save(newCoffee);
        return newCoffee;
    }


    @GetMapping(path = "/", params = "!name")
    public List<CoffeeEntity> getAll() {
        return coffeeRepository.list();
    }

    @GetMapping("/{id}")
    public CoffeeEntity getById(@PathVariable Long id) {
        CoffeeEntity coffee = coffeeRepository.getById(id);
        log.info("CoffeeEntity {}:", coffee);
        return coffee;
    }

    @GetMapping(path = "/", params = "name")
    public CoffeeEntity getByName(@RequestParam String name) {
        return coffeeRepository.getOne(new QueryWrapper<CoffeeEntity>().eq("NAME", name));
    }
}
